{
 "cells": [
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-26T02:49:04.509178Z",
     "start_time": "2025-06-26T02:49:04.498406Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# GPU\n",
    "import torch\n",
    "from torch import nn\n",
    "\n",
    "torch.device('cpu'), torch.device('cuda'), torch.device('cuda:1')"
   ],
   "id": "ed8f35568672e54d",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(device(type='cpu'), device(type='cuda'), device(type='cuda', index=1))"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-26T02:49:04.540280Z",
     "start_time": "2025-06-26T02:49:04.526240Z"
    }
   },
   "cell_type": "code",
   "source": "torch.cuda.device_count()",
   "id": "4e78ad79160a41a8",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-26T02:49:04.570869Z",
     "start_time": "2025-06-26T02:49:04.556135Z"
    }
   },
   "cell_type": "code",
   "source": [
    "def try_gpu(i=0):  #@save\n",
    "    \"\"\"如果存在，则返回gpu(i)，否则返回cpu()\"\"\"\n",
    "    if torch.cuda.device_count() >= i + 1:\n",
    "        return torch.device(f'cuda:{i}')\n",
    "    return torch.device('cpu')\n",
    "\n",
    "def try_all_gpus():  #@save\n",
    "    \"\"\"返回所有可用的GPU，如果没有GPU，则返回[cpu(),]\"\"\"\n",
    "    devices = [torch.device(f'cuda:{i}')\n",
    "             for i in range(torch.cuda.device_count())]\n",
    "    return devices if devices else [torch.device('cpu')]\n",
    "\n",
    "try_gpu(), try_gpu(10), try_all_gpus()"
   ],
   "id": "23e376e0d87924f5",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(device(type='cuda', index=0),\n",
       " device(type='cpu'),\n",
       " [device(type='cuda', index=0)])"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 10
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-26T02:49:08.981258Z",
     "start_time": "2025-06-26T02:49:08.968001Z"
    }
   },
   "cell_type": "code",
   "source": [
    "x = torch.tensor([1, 2, 3])\n",
    "x.device"
   ],
   "id": "9a6cfdc1cf8544ff",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "device(type='cpu')"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-26T02:49:32.523513Z",
     "start_time": "2025-06-26T02:49:32.218486Z"
    }
   },
   "cell_type": "code",
   "source": [
    "X = torch.ones(2, 3, device=try_gpu())\n",
    "X"
   ],
   "id": "2c2296cfe726fbf3",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[1., 1., 1.],\n",
       "        [1., 1., 1.]], device='cuda:0')"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-26T02:49:49.411045Z",
     "start_time": "2025-06-26T02:49:49.397026Z"
    }
   },
   "cell_type": "code",
   "source": [
    "Y = torch.rand(2, 3, device=try_gpu(1))\n",
    "Y"
   ],
   "id": "9ada2b3f3049acab",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[0.9050, 0.3548, 0.2565],\n",
       "        [0.1085, 0.3104, 0.3521]])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-26T02:52:16.464520Z",
     "start_time": "2025-06-26T02:52:16.263641Z"
    }
   },
   "cell_type": "code",
   "source": [
    "Z = X.cuda(1) #克隆操作（跨设备）\n",
    "print(X)\n",
    "print(Z)\n",
    "\"\"\"这里得有两块显卡才可以执行，简单来说两个GPU下执行矩阵之间计算必须通过拷贝方式放在同一块显卡下才可以执行，不然会报错\"\"\""
   ],
   "id": "9842d9c4d94d51b1",
   "outputs": [
    {
     "ename": "RuntimeError",
     "evalue": "CUDA error: invalid device ordinal\nCUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.\nFor debugging consider passing CUDA_LAUNCH_BLOCKING=1\nCompile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.\n",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mRuntimeError\u001B[0m                              Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[14], line 1\u001B[0m\n\u001B[1;32m----> 1\u001B[0m Z \u001B[38;5;241m=\u001B[39m \u001B[43mX\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mcuda\u001B[49m\u001B[43m(\u001B[49m\u001B[38;5;241;43m1\u001B[39;49m\u001B[43m)\u001B[49m\n\u001B[0;32m      2\u001B[0m \u001B[38;5;28mprint\u001B[39m(X)\n\u001B[0;32m      3\u001B[0m \u001B[38;5;28mprint\u001B[39m(Z)\n",
      "\u001B[1;31mRuntimeError\u001B[0m: CUDA error: invalid device ordinal\nCUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.\nFor debugging consider passing CUDA_LAUNCH_BLOCKING=1\nCompile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.\n"
     ]
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "Y + Z",
   "id": "1ca8fadc77275bf0"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "Z.cuda(1) is Z #同一块显卡下执行克隆操作还是自己",
   "id": "d84c4abf66dc0bcd"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.22"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
